package com.yuhong.reggie.controller;

import com.yuhong.reggie.common.R;
import com.yuhong.reggie.util.UUIDUtils;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String baseDir;

    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();

        //扩展名
        String substring = filename.substring(filename.lastIndexOf("."));

        //随机生成
        String newSubstring = UUIDUtils.getUUID()+ substring;
        //将文件保存到D:impl
        File file1 = new File(baseDir);
        if (!file1.exists()){
            file1.mkdirs();//创建
        }
        //进行保存
        file.transferTo(new File(baseDir+newSubstring));

        return R.success(newSubstring);
    }
    @RequestMapping("/download")
    public void download(@RequestParam("name") String fileName, HttpServletResponse response) throws IOException {
        //输入流
        FileInputStream inputStream = new FileInputStream(baseDir+fileName);
        //输出流
        ServletOutputStream outputStream = response.getOutputStream();

        IOUtils.copy(inputStream,outputStream);
    }
}
